
import bpy
from bpy_extras.io_utils import ExportHelper

from ossl._types.Animation import Animation
from ossl.formats.format_BVH import Format_BVH

class OSSL_OT_Animation_export_BVH(bpy.types.Operator, ExportHelper):
    bl_label = "OSSL Menu Animation Export BVH"
    bl_idname = "ossl.export_animation_bvh"
    bl_options = { 'REGISTER' }

    filename_ext = ".bvh"

    def draw(self, context): layout = self.layout

    @classmethod
    def poll(cls, context):
        return cls.getContextAction(context) != None
    
    @classmethod
    def getContextAction(cls, context):
        obj = context.object
        if not(obj): return None
        if not(obj.type == 'ARMATURE'): return None
        if not(obj.animation_data): return None
        if not(obj.animation_data.action): return None
        return obj.animation_data.action
        
    def execute(self, context):
        action = self.getContextAction(context)
        armature = context.object
        adj_mat = armature.data.bones["mPelvis"].matrix.inverted().to_4x4()
        print("\n\nbvh adj_mat:\n", adj_mat)
        anim = Animation(context.scene, armature, action, adj_mat)
        Format_BVH(anim.prepare_for_export()).export(self.filepath)
        print("Export BVH called")
        return { 'FINISHED' }

def OSSL_operator_Animation_export_BVH(self, comtext):
    self.layout.operator(OSSL_OT_Animation_export_BVH.bl_idname, text=".bvh", icon='FILE_TEXT')

import ossl.util as util

addon_keymaps = []

def register():
    print("registering: OSSL Type Animation Export BVH")
    bpy.utils.register_class(OSSL_OT_Animation_export_BVH)
    bpy.types.OSSL_MT_Animation_export.append(OSSL_operator_Animation_export_BVH)
    print("registered: OSSL Type Animation Export BVH")

def unregister():
    print("unregistering: OSSL Type Animation Export BVH")
    bpy.types.OSSL_MT_Animation_export.remove(OSSL_operator_Animation_export_BVH)
    bpy.utils.unregister_class(OSSL_OT_Animation_export_BVH)
    print("unregistered: OSSL Type Animation Export BVH")

if __name__ == "__main__":
    import ossl.util as util
    util.reset_addon()
